<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\BaseController;
use app\model\AdminLog;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class Log extends BaseController
{

    public function index()
    {
        $keyword=request()->param('keyword');
        $time=request()->param('time');

      $data=  AdminLog::with('admin')
            ->when($keyword,function ($query) use($keyword){
                $query->where('type',$keyword);
            })
            ->when($time,function ($query) use($time){
                $start=strtotime(explode(',',$time)[0]);
                $end=strtotime(explode(',',$time)[1]);
                $query->whereBetween('created_at',[$start,$end]);
            })->order('id','desc')->paginate(10);

        return $this->success($data);
    }

    public function excel()
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 设置表头
        $sheet->setCellValue('A1', '管理員');
        $sheet->setCellValue('B1', '修改參數');
        $sheet->setCellValue('C1', '類型');
        $sheet->setCellValue('D1', '操作時間');

        //设置宽度
        $sheet->getColumnDimension('A')->setWidth(10);
        $sheet->getColumnDimension('B')->setWidth(25);
        $sheet->getColumnDimension('C')->setWidth(10);
        $sheet->getColumnDimension('D')->setWidth(20);
        // 设置表格数据
        $data=AdminLog::with('admin')->select()->toArray();
        $row = 2;

        $type=[1=>'庫存',2=>'積分',3=>'優惠券',4=>'系統'];
        foreach ($data as $item) {

            $sheet->setCellValue('A' . $row, $item['admin']['username']);
            $sheet->setCellValue('B' . $row, $item['content']);
            $sheet->setCellValue('C' . $row, $type[$item['type']]);
            $sheet->setCellValue('D' . $row, $item['created_at']);

            $row++;
        }
        $filename = './uploads/活動日誌.xlsx';
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save($filename);
        return $this->success(ossUpload($filename)) ;
    }


}
